import 'dart:convert';

import 'package:android_intent_plus/android_intent.dart';
import 'package:bruno/bruno.dart';
import 'package:dio/dio.dart';
import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:loading_animation_widget/loading_animation_widget.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:sph_shipper/AppConfig/Config.dart';
import 'package:sph_shipper/Message/MessageCenter.dart';
import 'package:sph_shipper/SendGoods/AddGoodsFirst.dart';
import 'package:sph_shipper/SendGoods/DesignatedDriver.dart';
import 'package:sph_shipper/SendGoods/FrequentlyShippedSources.dart';
import 'package:sph_shipper/SendGoods/ShipmentHistory.dart';
import 'package:sph_shipper/SendGoods/SourceDetails.dart';
import 'package:url_launcher/url_launcher.dart';

import '../AppConfig/LocalStorage.dart';
import '../AppConfig/RouteAct.dart';
import '../AppConfig/ShowDialog.dart';
import '../Order/WaybillDetails/NoInvoicingSpecified.dart';
import '../http/NoLoadingGetApi.dart';
import '../http/NoLoadingPostApi.dart';
import '../http/api.dart';
import '../http/getapi.dart';
import '../l10n/messages.dart';
import 'ContactedDriverList.dart';
import 'package:platform/platform.dart';
class SendGoodsMain extends StatefulWidget {
  const SendGoodsMain({super.key,});

  @override
  State<SendGoodsMain> createState() => _SendGoodsMainState();
}

class _SendGoodsMainState extends State<SendGoodsMain> {

  int listType =1;
  List orderID =["111111","222222","333333",];
  List isExpandedList=[];
  List driverName=["张大帅","张二帅","张三帅","张四帅"];
  List dataList=[];
  ScrollController _scrollController = ScrollController();
  bool _isLoading = false;
  bool isLoading =false;
  int pageNum=1;
  bool isNoMore=false;
  @override
  void initState() {
    super.initState();

    getGoodsList(1);
    _scrollController.addListener(() {
      // 检查是否滚动到底部
      if (_scrollController.position.pixels == _scrollController.position.maxScrollExtent) {
        // 滚动到底部时加载更多数据

        _loadMoreData();
      }
    });
  }
  Future<void> _loadMoreData() async {
    // 加载更多数据后更新列表
    setState(() {
      if(dataList.length > 20*pageNum-1) {
        pageNum=pageNum+1;
        getGoodsList(pageNum);
      }
      _isLoading = false;
    });
  }
  //获取司机联系表
  Future<void> getChooseDriverList(String sourceId) async {
    getApiManager.getData(
      context, // 上下文对象，用于显示提示信息等
      'api/goods/goods/goods/getDriverCantact', // 您的API端点
      {"sourceId":sourceId}, // 查询参数，如果没有可以传递null
          (responseData) async {
        BrnToast.show(
          "发送成功",
          context,
          duration: BrnDuration.short,
        );
      },
    );
  }
  void getGoodsList(int current) async {
    String? token =await TokenManager.getToken();
    print(token);
    String?  shipperId= await UserIdManager.getUserID();
    print(shipperId);
    NoLoadinggetApiManager.getData(
      context,
      "api/goods/goods/shipperGoodsPage",
      {
        "shipperId":shipperId,
        "current":pageNum,
        "size":20,
      },
          (responseData) async {
            if (current==1) {
              setState(() {
                dataList = responseData['data']['records'];
              });

            }else{
              if(responseData['data']['records'].isNotEmpty) {
                setState(() {
                  isNoMore=false;
                  dataList.add(responseData['data']['records']);
                });
              }else{
                setState(() {
                  pageNum=pageNum-1;
                  isNoMore=true;
                });
              }
            }
      },
    );



  }
  void deleteBillAction(String id)async{

    ApiManager.postData(
      context,
      'api/goods/goods/offline',
      {
        "id":id,
      },
          (responseData) {
        setState(() {
          print(responseData);
          BrnToast.show("删除成功", context);
          getGoodsList(1);
        });
      },
    );
  }

  //置顶
  void goodsTopAction(String id,int top)async{
    NoLoadingApiManager.postData(
      context,
      'api/goods/goods/editTop',
      {
        "goodsId":id,
        "top": top==1?false:true
      },
          (responseData) {
        setState(() {
          BrnToast.show("设置成功", context);
          getGoodsList(1);
        });
      },
    );
  }

  Future _onRefresh() async {
    pageNum=1;
    getGoodsList(pageNum);

  }

  @override

  _makePhoneCall(String phoneNumber) async {
    if (LocalPlatform().isAndroid) {
      var status = await Permission.phone.status;
      if (status.isGranted) {
        // 权限已被授予
        // callPhone();
        final AndroidIntent intent = AndroidIntent(
          action: 'android.intent.action.CALL',
          data: Uri.encodeFull('tel:$phoneNumber'),
        );
        await intent.launch();
      } else if (status.isDenied) {
        // 权限被拒绝，但用户可以再次授权
        showCallPhoneFirstDialog(context);
        status = await Permission.phone.request();
        if (status.isGranted) {
          // 用户同意了权限
          // callPhone();
          final AndroidIntent intent = AndroidIntent(
            action: 'android.intent.action.CALL',
            data: Uri.encodeFull('tel:$phoneNumber'),
          );
          await intent.launch();
        } else {
          showCallPhoneDialog(context);
          // 用户拒绝权限，无法发起电话
          // 可以在此处展示信息提示用户需要权限
        }
      } else if (status.isPermanentlyDenied) {
        // 权限被永久拒绝，需要用户手动开启权限
        showCallPhoneDialog(context);
      }

    }else{
      final url =Uri.parse('tel:$phoneNumber');
      if (await canLaunchUrl(url)) {
        await launchUrl(url);
      } else {
        throw '无法拨打电话：$url';
      }
    }
  }

  Widget build(BuildContext context) {

    final screenSize = MediaQuery.of(context).size;
    var messages = AppLocalizations.of(context)!;
    return Scaffold(
      backgroundColor: MyColors.backgreyColor,
      appBar: AppBar(
        automaticallyImplyLeading: false,
        title:  Container(
          height: 25.h,
          width: 190.w,

          decoration: BoxDecoration(
              border: Border.all(
                color: MyColors.themeColor,
                width: 1.0.w,
              ),
              color: Colors.white,
              borderRadius: BorderRadius.all(Radius.circular(30))),
          child:Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              GestureDetector(
                child: Container(
                  width: 60.w,
                  height: 25.h,
                  decoration: BoxDecoration(
                      color: listType==1? MyColors.themeColor:Colors.white,
                      borderRadius: BorderRadius.all(Radius.circular(30))),
                  child: Center(
                    child: Text("发货中",style: TextStyle(fontSize: 13.sp,color:listType==1? Colors.white:Colors.black,fontWeight: listType==1?FontWeight.w600:FontWeight.w300),),
                  ),

                ),
                onTap: (){
                  setState(() {
                    listType=1;
                    getGoodsList(1);
                  });
                },
              ),
              GestureDetector(
                child: Container(
                  width: 60.w,
                  height: 25.h,
                  decoration: BoxDecoration(
                      color: listType==2? MyColors.themeColor:Colors.white,
                      borderRadius: BorderRadius.all(Radius.circular(30))),
                  child: Center(
                    child: Text("发货历史",style: TextStyle(fontSize: 13.sp,color:listType==2? Colors.white:Colors.black,fontWeight: listType==2?FontWeight.w600:FontWeight.w300),),
                  ),

                ),
                onTap: (){
                  setState(() {
                    listType=2;
                  });


                },
              ),
              GestureDetector(

                child: Container(
                  width:60.w ,
                  height: 25.h,
                  decoration: BoxDecoration(
                      color: listType==3? MyColors.themeColor:Colors.white,
                      borderRadius: BorderRadius.all(Radius.circular(30))),
                  child: Center(
                    child: Text("常发货源",style: TextStyle(fontSize: 13.sp,color:listType==3? Colors.white:Colors.black,fontWeight: listType==3?FontWeight.w600:FontWeight.w300),),
                  ),

                ),
                onTap: (){
                  setState(() {
                    listType=3;
                  });


                },
              ),
            ],
          ),
        ),

        centerTitle: true,
        backgroundColor: Colors.white,
        actions: [
          GestureDetector(
            child: Text("消息",style: TextStyle(color: Colors.black,fontSize: 14.sp),),
            onTap: (){
              Navigator.push( context, FadeRoute(page:MessageCenter()));
            },
          ),
          // Badge(label: Text("1"),),
          SizedBox(width: 10.w,),
        ],
      ),


      floatingActionButton: listType ==1?Container(
          margin: EdgeInsets.only(right: 10.w,bottom: 30.h),
        width: 86.0,
        height: 40.0,
        decoration: BoxDecoration(
          gradient: LinearGradient(
            begin: Alignment.topCenter,
            end: Alignment.bottomCenter,
            colors: [MyColors.themeColor, Color.fromRGBO(239,160,82,1)], // 设置渐变颜色
          ),
          borderRadius: BorderRadius.circular(30.0), // 设置圆角
        ),
        child: FloatingActionButton(
          onPressed: () {
            NoLoadinggetApiManager.getData(
              context,
              MyServiceUrl.getLoginUser,
              {},
                  (responseData) async {
                    if(responseData['data']['authStatus']==2) {
                   final result = await Navigator.push(context, FadeRoute(page: AddGoodsFirst(
                        dataMap: {}, editType: 1,
                      )));
                   if(result==null){
                     getGoodsList(1);
                   }
                    }else if(responseData['data']['authStatus']==1){
                      BrnToast.show("您的身份认证还在审核中", context);
                    }else{
                      BrnToast.show("请先进行身份认证", context);
                    }
              },
            );

          },
          elevation: 0,
          backgroundColor: Colors.transparent,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(30.0), // 设置圆角
          ),
          child: Text(
            '发 货',
            style: TextStyle(color: Colors.white,fontSize: 16.sp,fontWeight:FontWeight.w600),
          ),
        ),

      ):SizedBox(width: 0,),
      body:listType==2?ShipmentHistory():
          listType==3?FrequentlyShippedSources():
          EasyRefresh(
              header:
              ClassicHeader(
                dragText: '下拉刷新',
                armedText: '准备释放',
                readyText: '加载中...',
                processingText: '加载中...',
                processedText: '刷新成功',
                noMoreText: '暂无更多',
                failedText: '刷新失败',
                messageText: '刷新时间 %T',
              ),

            footer: ClassicFooter(
              dragText: '加载更多',
              armedText: '准备释放',
              readyText: '加载中...',
              processingText: '加载中...',
              processedText: '加载成功',
              noMoreText: '暂无更多',
              failedText: '加载失败',
              messageText: '加载时间 %T',
            ),
              onRefresh: _onRefresh,
              onLoad: dataList.length > 20*pageNum-1?_loadMoreData:null,
    child:
    // isLoading?
    //     Center(
    // child:
    // LoadingAnimationWidget.prograssiveDots(color: MyColors.themeColor, size: 50),
    // ):
    ListView(
      children: [


    Container(
        margin: EdgeInsets.only(top: 8.h,right: 10.w,left: 10.w),
        height: screenSize.height-160.h,
        child:dataList.isEmpty?BrnAbnormalStateWidget(
          img: Image.asset(
            'lib/Images/OrderList/发货中暂无货源.png',
            scale: 3.0,
          ),
          content: '暂无货源\n快去发货吧',
        ):
        ListView.builder(
          shrinkWrap:false,
          controller: _scrollController,
          itemCount: dataList.length+1,
          itemBuilder: (BuildContext context, int index) {
             if (index < dataList.length) {
               return   GestureDetector(
                 onTap:() async {
                   final result=await   Navigator.push( context, FadeRoute(page:SourceDetails(
                     id: dataList[index]['id'],
                     shipperId: dataList[index]['shipperId'], checkPage: 1,
                   )));
                   if(result !=null||result==null){
                     getGoodsList(1);
                   }
                 },
                 child: Container(
                   padding: EdgeInsets.only(right: 8.w, bottom: 8.h),
                   margin: EdgeInsets.only(bottom: 8.h),
                   decoration: BoxDecoration(
                       color: Colors.white,
                       borderRadius: BorderRadius.all(Radius.circular(10))),
                   child: Column(
                     crossAxisAlignment: CrossAxisAlignment.start,
                     children: [
                       Row(
                         // mainAxisAlignment: MainAxisAlignment.spaceBetween,
                         children: [
                           dataList[index]['sortCode'] == 1 ?
                           BrnTagCustom(
                             fontSize:9.sp,
                             tagText: '置顶',
                             fontWeight: FontWeight.w600,
                             backgroundColor: MyColors.themeColor,
                             tagBorderRadius: BorderRadius.only(
                                 topLeft: Radius.circular(5)),
                           ) : SizedBox(height: 10.h,),
                           if(dataList[index]['sortCode'] == 1)
                             SizedBox(width: 8.w,),
                           Row(
                             mainAxisAlignment: MainAxisAlignment.end,
                             children: [

                               if(dataList[index]['category']==1)
                                 Image.asset("lib/Images/OrderList/企业标签.png",width: 30.w,height: 18.h,),
                               if(dataList[index]['invoiceType']==1)
                                 SizedBox(width: 8.w,),
                               if(dataList[index]['invoiceType']==1)
                                 Image.asset("lib/Images/OrderList/专票标签.png",width: 30.w,height: 18.h,),
                             ],
                           ),
                         ],
                       ),



                       Row(
                         crossAxisAlignment: CrossAxisAlignment.center,
                         children: [
                           SizedBox(width: 18.w,),
                           Column(
                             children: [
                               Image.asset("lib/Images/OrderList/装icon.png",
                                 width: 13.w, height: 13.h,),
                               Image.asset(
                                 "lib/Images/OrderList/垂直虚线.png", width: 13.w,
                                 height: 10.h,),
                               if(dataList[index]["loadPlaceInfo"].length == 2&&dataList[index]["loadPlaceInfo"][1]!=null)
                                 Column(
                                   children: [
                                     Image.asset(
                                       "lib/Images/OrderList/装icon.png",
                                       width: 13.w, height: 13.h,),
                                     Image.asset(
                                       "lib/Images/OrderList/垂直虚线.png",
                                       width: 13.w, height: 10.h,),
                                   ],
                                 ),
                               if( dataList[index]["unloadPlaceInfo"].length == 2&&dataList[index]["unloadPlaceInfo"][1]!=null)
                                 Column(
                                   children: [
                                     Image.asset("lib/Images/OrderList/卸icon.png", width: 13.w, height: 13.h,),
                                     Image.asset("lib/Images/OrderList/垂直虚线.png", width: 13.w, height: 10.h,),
                                   ],
                                 ),
                               Image.asset("lib/Images/OrderList/卸icon.png",
                                 width: 13.w, height: 13.h,),
                             ],
                           ),
                           Column(
                             crossAxisAlignment: CrossAxisAlignment.start,
                             children: [
                               Container(
                                 width: screenSize.width - 60.w,
                                 child: Row(
                                   children: [
                                     Container(
                                            constraints: BoxConstraints(
                                            maxWidth: 170.w, // 限制文本最大宽度
                                            ),
                                       child: Text(
                                         dataList[index]["loadPlaceInfo"][0]["city"] +
                                             " " +
                                             dataList[index]["loadPlaceInfo"][0]["county"],
                                         style: TextStyle(
                                           color: Colors.black,
                                           fontSize: 13.sp,
                                           fontWeight: FontWeight.w600,
                                         ),
                                         overflow: TextOverflow.ellipsis,
                                       ),
                                     ),
                                     SizedBox(width: 4), // 添加一些间距
                                     Container(
                                       constraints: BoxConstraints(
                                         maxWidth: screenSize.width - 84.w - 120.w, // 限制文本最大宽度
                                       ),
                                       child: Text(
                                         dataList[index]["loadDay"] +
                                             " " +
                                             dataList[index]["loadTime"] +
                                             "点装货",
                                         overflow: TextOverflow.ellipsis,
                                         style: TextStyle(
                                           color: MyColors.textColor,
                                           fontSize: 12.sp,
                                         ),
                                       ),
                                     ),
                                   ],
                                 ),
                               ),
                        
                               SizedBox(height:10.h,),
                               if(dataList[index]["loadPlaceInfo"].length == 2&&dataList[index]["loadPlaceInfo"][1]!=null)
                                 Column(
                                   crossAxisAlignment: CrossAxisAlignment.start,
                                   children: [
                                     Row(
                                       children: [
                                         Text(
                                           dataList[index]["loadPlaceInfo"][1]["city"] +
                                               " " +
                                               dataList[index]["loadPlaceInfo"][1]["county"],
                                           style: TextStyle(color: Colors.black,
                                               fontSize: 13.sp,fontWeight: FontWeight.w600),),
                                       ],
                                     ),
                                     SizedBox(height:10.h,),
                                   ],
                                 ),
                               Container(

                                 width: screenSize.width - 60.w,
                                 child: Row(
                                   children: [
                                     Container(

                                       constraints: BoxConstraints(
                                         maxWidth: 170.w, // 限制文本最大宽度
                                       ),
                                       child: Text(
                                         dataList[index]["unloadPlaceInfo"][0]["city"] +
                                             " " +
                                             dataList[index]["unloadPlaceInfo"][0]["county"],
                                         style: TextStyle(
                                           color: Colors.black,
                                           fontSize: 13.sp,
                                           fontWeight: FontWeight.w600,
                                         ),
                                         overflow: TextOverflow.ellipsis,
                                       ),
                                     ),
                                     SizedBox(width: 4),
                                    if(dataList[index]["unloadDay"]!=null&&dataList[index]["unloadDay"]!="")
                                     Container(
                                       constraints: BoxConstraints(
                                         maxWidth: screenSize.width - 84.w - 120.w, // 限制文本最大宽度
                                       ),
                                       child: Text(
                                         dataList[index]["unloadDay"] +
                                             " " +
                                             dataList[index]["unloadTime"] +
                                             "点卸货",
                                         overflow: TextOverflow.ellipsis,
                                         style: TextStyle(
                                           color: MyColors.textColor,
                                           fontSize: 12.sp,
                                         ),
                                       ),
                                     ),
                                   ],
                                 ),
                               ),

                               if(dataList[index]["unloadPlaceInfo"].length == 2&&dataList[index]["unloadPlaceInfo"][1]!=null)
                                 Column(
                                   crossAxisAlignment: CrossAxisAlignment.start,
                                   children: [
                                     SizedBox(height:10.h,),
                                     Row(
                                       children: [
                                         Text(
                                           dataList[index]["unloadPlaceInfo"][1]["city"] + " " + dataList[index]["unloadPlaceInfo"][1]["county"],
                                           style: TextStyle(color: Colors.black, fontSize: 13.sp,fontWeight: FontWeight.w600),),
                                       ],
                                     ),

                                   ],
                                 ),

                             ],

                           ),

                         ],
                       ),
                       SizedBox(height: 8.h,),
                       Row(
                         mainAxisAlignment: MainAxisAlignment.spaceBetween,
                         children: [
                           Row(
                             children: [
                               SizedBox(width: 17.w,),
                               Text( dataList[index]["cargoInfo"][0]['cargoName'],style: TextStyle(color: MyColors.textColor,fontSize: 13.sp),),
                               if(dataList[index]["cargoInfo"][0]['cargoWeight']!=null)
                                 Text( ","+dataList[index]["cargoInfo"][0]['cargoWeight'].toString()+"吨",style: TextStyle(color: MyColors.textColor,fontSize: 13.sp)),
                               if(dataList[index]["cargoInfo"][0]['cargoVolume']!=null)
                                 Text( ","+ dataList[index]["cargoInfo"][0]['cargoVolume'].toString()+"方",style: TextStyle(color: MyColors.textColor,fontSize: 13.sp)),
                             ],
                           ),
                           Text(dataList[index]["createTime"].substring(5, 16),
                             style: TextStyle(
                                 color: MyColors.textColor, fontSize: 13.sp),),
                         ],
                       ),
                       Row(
                         children: [
                           SizedBox(width: 17.w,),
                           dataList[index]["vehicleLength"].contains(",")?
                           Text( dataList[index]["vehicleLength"].replaceAll(",", "米/")+"米",style: TextStyle(color: MyColors.textColor, fontSize: 13.sp),):
                           Text( dataList[index]["vehicleLength"]+"米",style: TextStyle(color: MyColors.textColor, fontSize: 13.sp),),
                           if(dataList[index]["vehicleModel"]!=null)
                             dataList[index]["vehicleLength"].contains(",")?
                             Text("丨"+dataList[index]["vehicleModel"].replaceAll(",", "/"),style: TextStyle(color: MyColors.textColor, fontSize: 13.sp),)
                           : Text("丨"+dataList[index]["vehicleModel"],style: TextStyle(color: MyColors.textColor, fontSize: 13.sp),),
                         ],
                       ),
                       if (int.parse(dataList[index]["type"].toString()) == 0)
                         Row(
                           crossAxisAlignment: CrossAxisAlignment.end,
                           children: [
                             SizedBox(width: 15.w,),
                             Text((dataList[index]["freight"]).toString(),
                               style: TextStyle(color: MyColors.themeColor,
                                   fontSize: 20.sp,
                                   fontWeight: FontWeight.w600),),
                             Column(
                               children: [
                                 Text("元/趟",  style: TextStyle(
                                     color: MyColors.themeColor,
                                     fontSize: 12.sp,
                                     fontWeight: FontWeight.w600), ),
                                 SizedBox(height: 3.h,),
                               ],
                             )
                           ],
                         ),
                       if (int.parse(dataList[index]["type"].toString()) == 1)
                         Row(
                           crossAxisAlignment: CrossAxisAlignment.end,
                           children: [
                             SizedBox(width: 15.w,),
                             Text("电议", style: TextStyle(
                                 color: MyColors.themeColor,
                                 fontSize: 16.sp,
                                 fontWeight: FontWeight.w600),),
                           ],
                         ),
                       if (dataList[index]["deposit"]!="0")
                         Row(
                           crossAxisAlignment: CrossAxisAlignment.center,
                           children: [
                             SizedBox(width: 15.w,),
                             Text("订金：¥", style: TextStyle(
                                 color: MyColors.themeColor,
                                 fontSize: 14.sp,
                                 fontWeight: FontWeight.w600),),
                             Text((dataList[index]["deposit"]).toString(),
                               style: TextStyle(color: MyColors.themeColor,
                                   fontSize: 14.sp,
                                   fontWeight: FontWeight.w600),),

                           ],
                         ),
                       Divider(color: MyColors.backgreyColor,),
                       // Row(
                       //   mainAxisAlignment: MainAxisAlignment.spaceBetween,
                       //   children: [
                           // SizedBox(),
                           // dataList[index]["driverContactSize"].toString()=="0"?
                           // GestureDetector(
                           //   child: Column(
                           //     children: [
                           //       Icon(Icons.publish,color: Colors.black,),
                           //       Text(dataList[index]["sortCode"] == 1 ? '取消置顶' : "置顶",style: TextStyle(color: Colors.black,fontSize: 10.sp),)
                           //     ],
                           //   ),
                           //   onTap: (){ goodsTopAction(dataList[index]['id'],dataList[index]['shipperId']);},
                           // ):SizedBox(),
                         
                           Row(
                             mainAxisAlignment: MainAxisAlignment.end,
                             children: [
                               GestureDetector(
                                 child:  Container(
                                   width: 80.w,
                                   height: 25.h,
                                   decoration: BoxDecoration(
                                     color: Colors.white,
                                     borderRadius: BorderRadius.circular(30.0),
                                     border: Border.all(
                                       color: MyColors.themeColor,
                                       width: 1.0,
                                     ),
                                   ),
                                   child: Center(child: Text("指定司机",style: TextStyle(fontSize: 14.sp,color: MyColors.themeColor,fontWeight: FontWeight.w600),),)
                                 ),
                                 onTap: ()async{
                                   final result=await Navigator.push( context, FadeRoute(page:DesignatedDriver(
                                              orderId: dataList[index]['id'],
                                              shipperId: dataList[index]['shipperId'], type: 1,
                                            )));
                                   if(result==null){
                                     getGoodsList(1);
                                   }
                                 },
                               ),


                               SizedBox(width: 4.w,),
                               GestureDetector(
                                 child:  Container(
                                     width: 50.w,
                                     height: 25.h,
                                     decoration: BoxDecoration(
                                       color: Colors.white,
                                       borderRadius: BorderRadius.circular(30.0),
                                       border: Border.all(
                                         color: MyColors.themeColor,
                                         width: 1.0,
                                       ),
                                     ),
                                     child: Center(child: Text("删除",style: TextStyle(fontSize: 14.sp,color: MyColors.themeColor,fontWeight: FontWeight.w600),),)
                                 ),
                                 onTap: (){
                                   showDialog(
                                     context: context,
                                     builder: (BuildContext context) {
                                       return BrnDialog(
                                         titleText: '提示',
                                         messageText:'确定删除该货源？',
                                         actionsWidget: [
                                           TextButton(
                                             onPressed: () {
                                               Navigator.of(context).pop();
                                             },
                                             child: Text("取消",style: TextStyle(color: Colors.black,fontSize: 14.sp),),
                                           ),
                                           TextButton(
                                             onPressed: () {
                                               Navigator.of(context).pop();
                                               deleteBillAction(dataList[index]["id"]);

                                             },
                                             child: Text("确定",style: TextStyle(color: MyColors.themeColor,fontSize: 14.sp),),
                                           ),
                                         ],
                                       );
                                     },
                                   );

                                 },
                               ),
                               SizedBox(width: 4.w,),
                               GestureDetector(
                                 child:  Container(
                                     width: 50.w,
                                     height: 25.h,
                                     decoration: BoxDecoration(
                                       color: Colors.white,
                                       borderRadius: BorderRadius.circular(30.0),
                                       border: Border.all(
                                         color: MyColors.themeColor,
                                         width: 1.0,
                                       ),
                                     ),
                                     child: Center(child: Text("编辑",style: TextStyle(fontSize: 14.sp,color: MyColors.themeColor,fontWeight: FontWeight.w600),),)
                                 ),
                                 onTap: ()async{
                                  final result=await Navigator.push( context, FadeRoute(page:AddGoodsFirst(
                                     dataMap: dataList[index], editType: 2,
                                   )));
                                  if(result!=null){
                                    getGoodsList(1);
                                  }
                                 },
                               ),

                               SizedBox(width: 4.w,),
                               GestureDetector(
                                 child:  Container(
                                     width: 50.w,
                                     height: 25.h,
                                     decoration: BoxDecoration(
                                       color: Colors.white,
                                       borderRadius: BorderRadius.circular(30.0),
                                       border: Border.all(
                                         color: MyColors.themeColor,
                                         width: 1.0,
                                       ),
                                     ),
                                     child: Center(child: Text("改价",style: TextStyle(fontSize: 14.sp,color: MyColors.themeColor,fontWeight: FontWeight.w600),),)
                                 ),
                                 onTap: ()async{
                                   final result = await showModalBottomSheet(
                                       context: context,
                                       isScrollControlled: true,
                                       isDismissible: false,
                                       // 设置为 false，点击外部区域不关闭
                                       enableDrag: false,
                                       // 设置为 false，禁用上滑手势关闭
                                       builder: (BuildContext context) {
                                         return MyBidSheet(
                                           id: dataList[index]['id'], goodsWeight:dataList[index]['cargoInfo'][0]['cargoWeight'].toString(), goodsValume: dataList[index]['cargoInfo'][0]['cargoVolume'].toString(), shipperId:dataList[index]['shipperId'], Price:dataList[index]['freight'], priceUnit: dataList[index]['priceUnit'] ,);
                                       }
                                   );
                                   if (result != null) {
                                     setState(() {
                                       getGoodsList(1);
                                     });
                                   }
                                 },
                               ),

                             ],
                           ),
                       //   ],
                       // ),

                       Divider(color: MyColors.backgreyColor,),

                       Row(
                         children: [
                           
                           Row(
                             children: [
                               SizedBox(width: 30.w,),
                               GestureDetector(
                                 child: Column(
                                children:[
                                  Icon(Icons.publish,color: Colors.black),
                                  Text( dataList[index]["sortCode"] == 1 ? '取消置顶' : "置顶", style: TextStyle(
                                    fontSize: 10,
                                    color: Colors.black,
                                  ),)
                                     ]
                             
                             ),
                                onTap: (){
                                  goodsTopAction(dataList[index]['id'],dataList[index]['sortCode']);
                                },
                               ),
                              SizedBox(width: 30.w,),
                               GestureDetector(
                                 child: Row(
                                   children: [
                                     Icon(Icons.phone_in_talk,color: MyColors.themeColor,),
                                     SizedBox(width: 4.w,),
                                     Text(dataList[index]["contactNum"].toString() + "人已联系", style: TextStyle(
                                         color: Colors.black, fontSize: 14.sp),),
                                   ],
                                 ),
                                 onTap: ()async{
                                   final result=await   Navigator.push( context, FadeRoute(page:SourceDetails(
                                     id: dataList[index]['id'],
                                     shipperId: dataList[index]['shipperId'], checkPage: 2,
                                   )));
                                   if(result !=null||result ==null){
                                     getGoodsList(1);
                                   }
                                 },
                               ),

                             ],
                           ),
                           // if ( dataList[index]["driverContactSize"]!=0)
                           // BrnIconButton(
                           //     name: isExpandedList[index] == 1 ? '收起' : '展开',
                           //     style: TextStyle(
                           //         color: Colors.black, fontSize: 12.sp),
                           //     direction: Direction.right,
                           //     padding: 4,
                           //     iconWidget: Icon(isExpandedList[index] == 1 ? Icons
                           //         .keyboard_arrow_up : Icons.keyboard_arrow_down,
                           //       color: MyColors.textColor, size: 24,),
                           //     onTap: () {
                           //       setState(() {
                           //         print(isExpandedList[index]);
                           //         print(isExpandedList);
                           //         isExpandedList[index] == 0
                           //             ? isExpandedList[index] = 1
                           //             : isExpandedList[index] = 0;
                           //       });
                           //     }),
                         ],
                       ),
                       // if(dataList[index]["driverContactSize"].toString()!="0")
                       // AnimatedContainer(
                       //   duration: Duration(milliseconds: 500),
                       //   height: isExpandedList[index] == 1 ? dataList[index]["driverContactSize"] >
                       //       3 ? 350.h : 30.h + dataList[index]["driverContactSize"] * 100.h : 0.0,
                       //   // height: 350.h,
                       //   color: Color.fromRGBO(206, 206, 206, 0.5),
                       //   child:
                       //   ListView(
                       //     physics: NeverScrollableScrollPhysics(),
                       //     children: [
                       //       Center(
                       //         child: Text("联系过后超过24小时，将不再存有记录。",
                       //           style: TextStyle(fontSize: 12.sp,
                       //               color: MyColors.themeColor),),
                       //
                       //       ),
                       //       Container(
                       //         height: dataList[index]["driverContactSize"] > 3 ? 310.h : dataList[index]["driverContactSize"] * 100.h,
                       //         child: ListView.builder(
                       //             physics: NeverScrollableScrollPhysics(),
                       //             shrinkWrap: false,
                       //             itemCount: dataList[index]["returnDriverContact"].length,
                       //             itemBuilder: (BuildContext context,
                       //                 int inPath) {
                       //               return Container(
                       //                 margin: EdgeInsets.only(
                       //                     top: 8.h, left: 15.w, right: 15.w),
                       //                 decoration: BoxDecoration(
                       //                     color: Colors.white,
                       //                     borderRadius: BorderRadius.all(Radius.circular(10))),
                       //                 padding: EdgeInsets.all(10.w),
                       //                 child: Column(
                       //
                       //                   children: [
                       //
                       //                     Row(
                       //                       mainAxisAlignment: MainAxisAlignment.spaceBetween,
                       //                       children: [
                       //                         Row(
                       //                           children: [
                       //                             Image.asset("lib/Images/login/抖音登录.png",
                       //                               width: 40.w, height: 40.h,),
                       //                             SizedBox(width: 8.w,),
                       //                             Column(
                       //                               crossAxisAlignment: CrossAxisAlignment.start,
                       //                               children: [
                       //                                 Row(
                       //                                   children: [
                       //
                       //                                     Text(dataList[index]["returnDriverContact"][inPath]['driverName'],
                       //                                       style: TextStyle(
                       //                                           color: Colors.black, fontSize: 13.sp),),
                       //                                     Row(
                       //                                       children: List.generate(index + 2, (starIndex) {
                       //                                         return Icon(
                       //                                             Icons.star, color: Colors.yellow, size: 20.0);
                       //                                       }),
                       //                                     ),
                       //                                   ],
                       //                                 ),
                       //                                 Row(
                       //                                   children: [
                       //                                     BrnTagCustom(
                       //                                       tagText: dataList[index]["returnDriverContact"][inPath]['vehicleNum'],
                       //                                       backgroundColor: MyColors.backgreyColor,
                       //                                       textColor: Colors.black,
                       //                                       maxWidth: 40.w,
                       //                                       fontSize: 10.sp,
                       //                                     ),
                       //                                     BrnTagCustom(
                       //                                       tagText: dataList[index]["returnDriverContact"][inPath]['vehicleLength']+"米",
                       //                                       backgroundColor: MyColors
                       //                                           .backgreyColor,
                       //                                       textColor: Colors
                       //                                           .black,
                       //                                       maxWidth: 40.w,
                       //                                       fontSize: 10.sp,
                       //                                     ),
                       //                                     BrnTagCustom(
                       //                                       tagText: dataList[index]["returnDriverContact"][inPath]['vehicleType'],
                       //                                       backgroundColor: MyColors.backgreyColor,
                       //                                       textColor: Colors.black,
                       //                                       fontSize: 10.sp,
                       //                                       maxWidth: 40.w,
                       //                                     ),
                       //                                   ],
                       //                                 ),
                       //
                       //                               ],
                       //                             ),
                       //                           ],
                       //                         ),
                       //
                       //
                       //                         Column(
                       //                           crossAxisAlignment: CrossAxisAlignment
                       //                               .end,
                       //                           children: [
                       //                             Container(
                       //                               width: 100.w,
                       //                               child:Text(dataList[index]["returnDriverContact"][inPath]['createTime'], style: TextStyle(overflow: TextOverflow.ellipsis, color: MyColors.textColor, fontSize: 12.sp),),
                       //                             ),
                       //                             Container(
                       //                               width: 50.w,
                       //                               height: 15.h,
                       //                               color: Color.fromRGBO(251, 236, 228, 1),
                       //                               child: Row(
                       //                                 mainAxisAlignment: MainAxisAlignment.center,
                       //                                 children: [
                       //                                   Image.asset("lib/Images/OrderList/拨入拨出电话icon.png", width: 12.w, height: 12.h,),
                       //                                   Text("拨出", style: TextStyle(color: MyColors.themeColor, fontSize: 10.sp),)
                       //                                 ],
                       //                               ),
                       //                             ),
                       //                           ],
                       //
                       //                         ),
                       //                       ],
                       //                     ),
                       //                     SizedBox(height: 8.h,),
                       //                     Row(
                       //                       mainAxisAlignment: MainAxisAlignment.spaceBetween,
                       //                       children: [
                       //                         Image.asset("lib/Images/OrderList/IMicon.png", width: 24.w, height: 24.h,),
                       //                         Row(
                       //                           children: [
                       //                             Container(
                       //                               height: 30.h,
                       //                               child:   BrnSmallMainButton(
                       //                               title: '指定承运',
                       //                               textColor: Colors.white,
                       //                               bgColor: MyColors.themeColor,
                       //                               radius: 30,
                       //                               fontSize: 13.sp,
                       //                               width: 80.w,
                       //                               onTap: () {
                       //                                 Navigator.push( context, FadeRoute(page:NoInvoicingSpecified( carMap: dataList[index]["returnDriverContact"][inPath], goodsMap: dataList[index],)));
                       //                               },
                       //                             ),
                       //                             ),
                       //                             SizedBox(width: 8.w,),
                       //                            Container(
                       //                              height: 30.h,
                       //                              child:   BrnSmallOutlineButton(
                       //                                title: '电话联系',
                       //                                textColor: MyColors.themeColor,
                       //                                lineColor: MyColors.themeColor,
                       //                                radius: 30,
                       //                                fontSize: 13.sp,
                       //                                width: 80.w,
                       //                                onTap: () {
                       //                                  _makePhoneCall(dataList[index]["returnDriverContact"][inPath]['phoneNum']);
                       //                                },
                       //                              ) ,
                       //                            ),
                       //
                       //                           ],
                       //                         ),
                       //                       ],
                       //                     )
                       //                   ],
                       //                 ),
                       //               );
                       //             }
                       //         ),
                       //       ),
                       //       // if (dataList[index]["driverContactSize"]>3)
                       //         GestureDetector(
                       //           child: Center(
                       //             child: Text("查看更多>", style: TextStyle(
                       //                 color: Colors.black, fontSize: 12.sp)),
                       //           ),
                       //
                       //           onTap: () {
                       //             Navigator.push( context, FadeRoute(page:ContactedDriverList(dataList: dataList[index]["returnDriverContact"], goodsMap: dataList[index],)));
                       //           },
                       //         ),
                       //
                       //
                       //     ],
                       //   ),
                       //
                       // ),
                     ],
                   ),

                 ),
               );

             }else{
               return _isLoading
                   ? Padding(
                 padding: EdgeInsets.all(8.0),
                 child: Center(
                   child: CircularProgressIndicator(),
                 ),
               )
                   : Container();
             }
          },
        ),

      ),
      ],
    ),
    ),

    );
  }
}
class MyBidSheet extends StatefulWidget {
  const MyBidSheet({super.key, required this.id, required this.goodsWeight, required this.goodsValume, required this.shipperId, required this.Price, required this.priceUnit});
  final String id;
  final String shipperId;
  final String goodsWeight;
  final String goodsValume;
  final String Price;
  final int priceUnit;
  @override
  State<MyBidSheet> createState() => _MyBidSheetState();
}

class _MyBidSheetState extends State<MyBidSheet> {
  String MyBid="";
  List<String> BidTypeList=["趟","方","吨"];
  int BidType =0;
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    MyBid=(widget.Price).toString();
    _textEditingController.text = MyBid;
    // BidType=widget.priceUnit-1;
  }
  void editBidAction(String sourceId,String shipperId,int priceUnit)async {
    ApiManager.postData(
      context,
      'api/goods/goods/editFreight',
      {
        "id": sourceId,
        "price": MyBid,
        "shipperId":shipperId,
        "priceUnit":priceUnit,
      },
          (responseData) {
        setState(() {
          BrnToast.show("修改成功", context);
          Navigator.pop(context,"success");
        });
      },
    );
  }
  TextEditingController _textEditingController = TextEditingController();

    @override
  Widget build(BuildContext context) {
    return Container(
      padding: EdgeInsets.only(left: 20.w,right: 20.w),
      decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.all(Radius.circular(10))),
      height: 500.h,
      child: Column(
        children: [
          SizedBox(height: 10.h,),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              GestureDetector(
                child: Row(
                    children:[
                      Text("取消",style: TextStyle(color: Colors.black,fontSize: 14.sp),),
                    ]
                ),
                onTap: (){
                  Navigator.pop(context);
                },
              ),
              Text("我的出价",style: TextStyle(color: Colors.black,fontSize: 16.sp,fontWeight: FontWeight.w600),),
              Row(
                children: [
                  GestureDetector(
                    child: Container(
                      width:50.w,
                      height:20.h,
                      decoration: BoxDecoration(
                          color: MyColors.themeColor,
                          borderRadius: BorderRadius.all(Radius.circular(20))),
                      child: Center(
                        child: Text("确认",style: TextStyle(color: Colors.white,fontSize: 14.sp),),
                      ),
                    ),
                    onTap: (){
                      if (MyBid=="") {
                        BrnToast.show("请填写运费", context);
                      }else if(BidType==-1){
                        BrnToast.show("请选择运费类型", context);
                      }else{
                      // if(BidType==2){
                      //   MyBid= (double.parse(MyBid)*double.parse(widget.goodsWeight)).toStringAsFixed(2);
                      // }else if(BidType==1) {
                      // MyBid= (double.parse(MyBid)*double.parse(widget.goodsValume)).toStringAsFixed(2);
                      // }else{
                        // if (MyBid.contains(".")) {
                        //   // 如果字符串中包含点
                        //   List<String> parts = MyBid.split(".");
                        //   // 拆分字符串
                        //
                        //   if (parts[1].length == 2) {
                        //     // 如果点后面有两位
                        //     MyBid = MyBid.replaceAll(".", "");
                        //   } else if (parts[1].length == 1) {
                        //     // 如果点后面有一位
                        //     MyBid = MyBid.replaceAll(".", "") + "0";
                        //   }
                        // }else{
                        // MyBid=MyBid;
                        //   MyBid=(int.parse(MyBid)).toString();
                        // }
                      // }
                      print(MyBid);
                        editBidAction(widget.id,widget.shipperId,(BidType+1));
                      }
                    },
                  ),

                ],
              ),
            ],
          ),
          SizedBox(height: 15.h,),
          Row(
            children: [
              if(widget.goodsWeight!="null")
                Text("货物重量${widget.goodsWeight}吨",style: TextStyle(color: MyColors.textColor,fontSize: 13.sp),),
              if(widget.goodsWeight!="null")
              SizedBox(width: 10.w,),
              if(widget.goodsValume!="null")
                Text("货物重量${widget.goodsValume}方",style: TextStyle(color: MyColors.textColor,fontSize: 13.sp),),
            ],
          ),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [

              Row(
                children: [
                  Text("*",style: TextStyle(color: MyColors.themeColor),),
                  Text("请确定计价单位",style: TextStyle(color: Colors.black,fontSize: 14.sp),),
                ],
              ),

              Row(
                children: [
                  BrnSmallMainButton(
                    title: '趟',
                    width: 40.w,
                    fontSize: 14.sp,
                    fontWeight: FontWeight.w100,
                    textColor:BidType==0?MyColors.themeColor: Colors.black,
                    bgColor:BidType==0?Color.fromRGBO(251, 236, 228, 1) :MyColors.backgreyColor,
                    onTap: () {
                      setState(() {
                        BidType =0;
                        print(widget.goodsWeight+"   "+widget.goodsValume);
                      });

                    },
                  ),
                  SizedBox(width: 4.w,),
                  if(widget.goodsWeight!="null")
                  BrnSmallMainButton(
                  title: '吨',
                  width: 40.w,
                    fontSize: 14.sp,
                  fontWeight: FontWeight.w100,
                  textColor:BidType==2?MyColors.themeColor: Colors.black,
                  bgColor:BidType==2?Color.fromRGBO(251, 236, 228, 1) :MyColors.backgreyColor,
                  onTap: () {
                    setState(() {
                      BidType =2;
                    });

                  },
                ),
                  SizedBox(width: 4.w,),
                  if(widget.goodsValume!="null")
                  BrnSmallMainButton(
                  title: '方',
                  width: 40.w,
                    fontSize: 14.sp,
                  fontWeight: FontWeight.w100,
                  textColor:BidType==1?MyColors.themeColor: Colors.black,
                  bgColor:BidType==1?Color.fromRGBO(251, 236, 228, 1) :MyColors.backgreyColor,
                  onTap: () {
                    setState(() {
                      BidType =1;
                    });

                  },
                ),
                ],
              )


            ],
          ),
          SizedBox(height: 15.h,),
          Container(
            height: 44.h,
            padding: EdgeInsets.only(left: 15.w,right: 15.w),
            decoration: BoxDecoration(
                color: MyColors.backgreyColor,
                borderRadius: BorderRadius.all(Radius.circular(10))),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Row(
                  children: [
                    Text("运费",style: TextStyle(color: Colors.black,fontSize: 14.sp,),),
                    SizedBox(width: 20.w,),
                    Container(width: 1.w,height: 20.h,color: MyColors.hintColor,),
                  ],
                ),
                Row(
                  children: [
                    Container(
                      width:100.w,
                      height: 30.h,
                      child:  TextField(
                        controller: _textEditingController,
                        decoration: InputDecoration(
                          hintText: "",
                          hintStyle:TextStyle(fontSize: 14.sp,color: Colors.black),
                          filled: true,

                          fillColor: MyColors.backgreyColor,
                          border: InputBorder.none,
                          alignLabelWithHint: true,

                          contentPadding: EdgeInsets.symmetric(vertical: 8.0.h, horizontal: 0.0.w),
                        ),
                        keyboardType: TextInputType.number,
                        textAlign: TextAlign.right,
                        style: TextStyle(color: Colors.black),
                        onChanged: (value) {
                          setState(() {
                            print(value);
                              MyBid =value;

                          });
                        },
                      ),
                    ),
                    SizedBox(width: 20.w,),
                    Text(BidType==0? "元/趟":BidType==2?"元/吨":"元/方",style: TextStyle(color: MyColors.themeColor,fontSize: 14.sp,),),
                  ],
                ),
              ],
            ),
          ),
          SizedBox(height: 10.h,),
          Row(
            children: [
              Text("总费用为：",style: TextStyle(color: Colors.black,fontSize: 14.sp,),),
              if (BidType==0)
                Text("¥" + MyBid, style: TextStyle(color: MyColors.themeColor,fontSize: 14.sp,),),
              if(BidType==2&&MyBid!="")
                Text("¥"+(double.parse(MyBid)*double.parse(widget.goodsWeight)).toStringAsFixed(2),style: TextStyle(color: MyColors.themeColor,fontSize: 14.sp,),),
              if(BidType==1&&MyBid!="")
              Text("¥"+ (double.parse(MyBid)*double.parse(widget.goodsValume)).toStringAsFixed(2),style: TextStyle(color: MyColors.themeColor,fontSize: 14.sp,),),
            ],
          )
        ],
      ),
    );
  }
}